//
//  WLLocalFileHandle.m
//  WanLian
//
//  Created by 123456 on 2019/1/7.
//  Copyright © 2019 wanlian. All rights reserved.
//

#import "WLLocalFileHandle.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface WLLocalFileHandle ()

@property (nonatomic, strong) NSURL *fileURL;
@property (nonatomic, strong) ALAssetsLibrary *assetLibrary;
@property (nonatomic, strong) ALAssetRepresentation *rep;
@end
@implementation WLLocalFileHandle
+ (instancetype)fileHandleForReadingAtPath:(NSURL *)loacalFileURL isReadyBlock:(void (^)(BOOL isReady))successBlock{
    WLLocalFileHandle *fileHandel = [[self alloc] init];
    fileHandel.fileURL = loacalFileURL;
    fileHandel.assetLibrary = [[ALAssetsLibrary alloc] init];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __weak typeof(fileHandel) weakFileHandle = fileHandel;
        [fileHandel.assetLibrary assetForURL:loacalFileURL resultBlock:^(ALAsset *asset) {
            ALAssetRepresentation *rep = [asset defaultRepresentation];
            weakFileHandle.rep = rep;
            if (successBlock) {
                successBlock(rep ? YES : NO);
            }
        } failureBlock:^(NSError *error) {
            if (successBlock) {
                successBlock(NO);
            }
        }];
    });
    return fileHandel;
}

- (NSData *)readDataAtOffset:(long long)offset lentgth:(unsigned long)size {
    Byte *buffer = (Byte*)malloc((unsigned long)size);
    NSUInteger buffered = [self.rep getBytes:buffer fromOffset:offset length:((unsigned long)size) error:nil];
    if (buffered == 0) {
        return nil;
    } else {
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
        return data;
    }
}
- (void)closeFile {
    self.assetLibrary = nil;
    
}
@end
